//
//  BabyDetailViewController.m
//  parent
//
//  Created by 闫珍 on 15/6/2.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "BabyDetailViewController.h"
#import "CellStyleTeacher.h"
#import "UserDao.h"
#import "CameraGalleryManager.h"
#import "AFAppClient.h"
#import "UIImageView+WebCache.h"
#import "ChangeBabyNameViewController.h"
#import "JoinClassViewController.h"
#import "IQKeyboardManager.h"
#import "NetWorkManager.h"
#import "JsonUtil.h"
#import "AppDelegate.h"


@interface BabyDetailViewController ()<UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIImageView *babyAvatar;
@property (nonatomic,copy) NSString *babyY;
@property (nonatomic,copy) NSString *babyM;
@property (nonatomic,copy) NSString *babyD;
@property BabyInfo *babyinfo;
@property NSUInteger babyS;
@property (nonatomic,strong) NSArray *sexs;
@property UIDatePicker *datePicker;
@property UIPickerView *pickerView;
@property UITextField *textField;
@property UITextField *textField1;
@end

@implementation BabyDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self customView];
    _babyinfo =[[UserDao getInstance]getCurrentBaby];
    [self refreshData];
    _sexs = @[@"男",@"女"];
    [[IQKeyboardManager sharedManager]setEnable:YES];
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _babyinfo =[[UserDao getInstance]getCurrentBaby];
    [self.tableview reloadData];
}
-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"宝贝信息";
    [self.navigationController.navigationBar setBarTintColor:UIColorMake(252,74,74)];
    self.navigationController.navigationBar.shadowImage = nil;
    self.navigationController.navigationBar.translucent = NO;
    [self.deleteBtn setTintColor:UIColorMake(255, 93, 93)];
    [self.view setBackgroundColor:DefaultViewColor];
    [self.deleteBtn setBackgroundColor:[UIColor whiteColor]];
    
    _datePicker = [[UIDatePicker alloc]init];
    [_datePicker setMaximumDate:[NSDate date]];
    [_datePicker setMinimumDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365 *20]];
    [_datePicker setDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365*5]];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    [_datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 260, 0, 0)];
    _textField.placeholder=@"";
    [_textField setInputView:_datePicker];
    [self.view addSubview:_textField];
    //_textField.hidden = YES;
    
    _tableview.alwaysBounceVertical=NO;
    
    _babyM=@"";
    _babyY=@"";
    _babyD = @"";
    [_deleteBtn setHidden:YES];
    
    _pickerView = [[UIPickerView alloc] init];
    
    [_pickerView sizeToFit];
    _pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.showsSelectionIndicator = YES;
    
    _textField1 = [[UITextField alloc]initWithFrame:CGRectMake(0, 190, 0, 0)];
    [_textField1 setInputView:_pickerView];
    [self.view addSubview:_textField1];

    _babyS=1;
    
    [_tableview setBackgroundColor:DefaultViewColor];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}
-(void)backButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString *CellIdentifier = @"CellStyleTeacher";
    
    CellStyleTeacher *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CellStyleTeacher" owner:self options:nil];
        cell = (CellStyleTeacher *)[nibArr objectAtIndex:0];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (section) {
            case 0:
                if (row == 0) {
                    cell.title.text = @"姓名";
                    cell.info.text =_babyinfo.cname;
                }else if (row == 1){
                    cell.title.text = @"性别";
                    if(_babyinfo.sex ==1){
                        cell.info.text = @"男";
                    }else{
                        cell.info.text = @"女";
                    }
                }
                break;
            case 1:
                if (row == 0) {
                    cell.title.text = @"生日";
                    cell.info.text = [NSString stringWithFormat:@"%ld.%ld.%ld",_babyinfo.birthy,_babyinfo.birthm,_babyinfo.birthd];
                }
                break;
            case 2:
                if(row==0){
                    cell.title.text = @"班级";
                    if(_babyinfo.classid==0){
                        cell.info.text = @"添加班级";
                    }else{
                        cell.info.text=_babyinfo.classname;
                    }
                }
                break;
                
        }
    }
    return cell;
}
#pragma mark ----------关于性别选择---------------
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_sexs objectAtIndex:row];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _sexs.count;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    debugLog(@"选择的性别是：%@",[_sexs objectAtIndex:row]);
    
    _babyS = row +1;
    _babyinfo.sex = _babyS;
    [self.tableview reloadData];
    
    NSDictionary *param = @{@"utype":@(1),@"uid":@([[UserDao getInstance]getUserId]),@"token":[[UserDao getInstance]getAccessToken],@"cid":@([[UserDao getInstance]getCurrentBaby].cid),
                            @"sex":@(_babyS)
                            };
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_MODIFY_CSEX data:[JsonUtil convertDictionaryToJson:param] FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            //NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue]== 1) {
                    [[BabyDao getInstance]updateBabyInfo:@{@"sex":@(_babyS)} withCid:_babyinfo.cid];
                    ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                }else{
                    
                }
            }else{
               
            }
        }
    }];

}

#pragma mark ----------关于生日选择---------------

-(void)changeDate:(UIDatePicker *)picker
{
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy.MM.dd"];

    [format setDateFormat:@"yyyy"];
    _babyY =[format stringFromDate:picker.date];
    [format setDateFormat:@"MM"];
    _babyM = [format stringFromDate:picker.date];
    [format setDateFormat:@"dd"];
    _babyD = [format stringFromDate:picker.date];
    
    _babyinfo.birthy = [_babyY integerValue];
    _babyinfo.birthm = [_babyM integerValue];
    _babyinfo.birthd = [_babyD integerValue];
    [self.tableview reloadData];
    NSDictionary *param = @{@"utype":@(1),@"uid":@([[UserDao getInstance]getUserId]),@"token":[[UserDao getInstance]getAccessToken],@"cid":@([[UserDao getInstance]getCurrentBaby].cid),
                            @"birthy":_babyY,
                                @"birthm":_babyM,
                                @"birthd":_babyD
                            };
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_MODIFY_CBIRTHDAY data:[JsonUtil convertDictionaryToJson:param] FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            //NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue]== 1) {
                    [[BabyDao getInstance]updateBabyInfo:@{@"birthy":_babyY,@"birthm":_babyM,@"birthd":_babyD} withCid:_babyinfo.cid];
                     ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                }else{
                    
                }
            }else{
                
            }
        }
    }];

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (section == 0 && row == 0) {//修改姓名
        [self changeName];
    }else if (section == 0 && row == 1) {//修改性别
        [self changeSex];
        
    }else if (section == 1 && row == 0) {//修改生日
        [self changeBirth];
        
    }else if (section == 2 && row == 0) {//班级
        if(_babyinfo.classid==0){
            [self joinClass];
        }
        
    }
}

-(void)changeSex
{
    [_textField1 becomeFirstResponder];
}
-(void)changeBirth
{
    [_textField becomeFirstResponder];
}

-(void)joinClass
{
    JoinClassViewController *joinClass = [[JoinClassViewController alloc]init];
    BabyInfo *baby = [[UserDao getInstance]getCurrentBaby];
    joinClass.babyid = baby.cid;
    [self.navigationController pushViewController:joinClass animated:YES];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)changeName
{
    ChangeBabyNameViewController *change = [[ChangeBabyNameViewController alloc]init];
    change.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:change
                                         animated:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else{
        return 1;
    }
}

//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//设置头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 2;
}
- (IBAction)doneDelete:(id)sender {
    
}

- (IBAction)uploadAvatar:(id)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
    [sheet showInView:self.view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    NSString *default_icon = @"";
    if (_babyinfo.sex == 1) { //男孩
        default_icon = @"default_avatar";
    }else{ //女孩
        default_icon = @"default_avatar_girl";
    }
    
    [_babyAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",AVATAR_HEADER,_babyinfo.cavatar]]placeholderImage:[UIImage imageNamed:default_icon]];
}

- (BOOL)checkCamera {
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if(!isCamera) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备没有摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //    UIImagePickerControllerSourceType sourceType;
    if(buttonIndex == 0) {
        if([self checkCamera]){
            //            sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self openGallery:sourceType];
            [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
                if (img) {
                    _babyAvatar.image = img;
                    NSDictionary *param = @{@"utype":@(1),@"childid":@(_babyinfo.cid),@"image.jpg":img,@"message":PARENT_POST_BABY_AVATAR};
                    [[AFAppClient sharedManager]postWithURL:SERVER_URL withParameters:param success:^(NSDictionary *responseObject) {
                        if([[responseObject objectForKey:@"retCode"] integerValue]== 1){
                            NSString *avatar_url =[responseObject objectForKey:@"avatar"];
                            [[BabyDao getInstance]updateBabyInfo:@{@"cavatar":avatar_url} withCid:_babyinfo.cid];
                             ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                        }
                    } failure:^(NSError *error) {
                        
                    }];
                }
            }];
        }else{
            return;
        }
    }else if(buttonIndex == 1){
        //        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //        [self openGallery:sourceType];
        [[CameraGalleryManager getInstanse] gallerySelect:self finishBlock:^(UIImage *img, NSString * avaURL) {
            if (img) {
                _babyAvatar.image = img;
                NSDictionary *param = @{@"utype":@(1),@"childid":@(_babyinfo.cid),@"image.jpg":img,@"message":PARENT_POST_BABY_AVATAR};
                [[AFAppClient sharedManager]postWithURL:SERVER_URL withParameters:param success:^(NSDictionary *responseObject) {
                    if([[responseObject objectForKey:@"retCode"] integerValue]== 1){
                        NSString *avatar_url =[responseObject objectForKey:@"avatar"];
                        [[BabyDao getInstance]updateBabyInfo:@{@"cavatar":avatar_url} withCid:_babyinfo.cid];
                        ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                    }
                } failure:^(NSError *error) {
                    
                }];
                
            }
        }];
    }
}

-(void)openGallery:(UIImagePickerControllerSourceType) source{
    //初始化类
    UIImagePickerController *pick = [[UIImagePickerController alloc] init];
    //指定图片来源
    pick.sourceType = source;
    //表示用户可编辑图片。
    pick.allowsEditing = YES;
    //代理
    pick.delegate = self;
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info {
    
    UIImage *image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
    NSLog(@"%@", image);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
